package com.gitee.dolt.boot.properties;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.File;

/**
 * 客户端认证配置
 *
 * @author LYH
 */
@ConfigurationProperties(prefix = BootProperties.PREFIX)
@Data
@NoArgsConstructor
@Slf4j
public class BootProperties {
    public static final String PREFIX = "dolt.boot";

    private boolean printBean = false;

    private CorsProperties cors = new CorsProperties();
    private LockProperties lock = new LockProperties();
    private DecryptProperties decrypt = new DecryptProperties();

    @Data
    public static class CorsProperties {

        private boolean allowCredentials = true;
        /**
         * 放行哪些原始域
         */
        private String allowedOrigin = "*";
        /**
         * 放行哪些原始域(头部信息)
         */
        private String allowedHeader = "*";
        /**
         * 放行哪些原始域(请求方式)
         */
        private String allowedMethod = "*";
        /**
         * 匹配路径
         */
        private String path = "/**";
    }

    @Data
    public static class LockProperties {
        /**
         * 是否启用锁
         */
        private Boolean enabled = true;
    }

    @NoArgsConstructor
    @ToString
    public static class DecryptProperties {
        /**
         * 是否启用数据加密
         */
        @Getter
        @Setter
        private Boolean enabled = true;

        /**
         * 公钥路径
         */
        @Getter
        @Setter
        private String rsaPubPath;

        /**
         * 私钥路径
         */
        @Getter
        @Setter
        private String rsaPriPath;

        private String rsaPub;

        private String rsaPri;

        public String getRsaPub() {
            if (StrUtil.isEmpty(rsaPub)) {
                init();
            }
            return rsaPub;
        }

        public String getRsaPri() {
            if (StrUtil.isEmpty(rsaPri)) {
                init();
            }
            return rsaPri;
        }

        public void init() {
            File rsaPubFile = FileUtil.file(rsaPubPath);
            File rsaPriFile = FileUtil.file(rsaPriPath);
            if (FileUtil.exist(rsaPubFile) && FileUtil.exist(rsaPriFile)) {
                this.rsaPub = FileUtil.readUtf8String(rsaPubFile);
                this.rsaPri = FileUtil.readUtf8String(rsaPriFile);
            } else {
                RSA rsa = SecureUtil.rsa();
                this.rsaPub = rsa.getPublicKeyBase64();
                this.rsaPri = rsa.getPrivateKeyBase64();
                log.info("---------rsa密钥未配置，系统自动生成---------");
                log.info("rsaPub->{}", rsaPub);
                log.info("rsaPri->{}", rsaPri);
            }
        }
    }


}
